package org.ptkparty.client.view.place;

import org.ptkparty.client.model.PlaceProxy;
import org.ptkparty.client.ui.CustomValueBoxEditorDecorator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.NumberLabel;
import com.google.gwt.user.client.ui.Widget;
import com.google.maps.gwt.client.GoogleMap;
import com.google.maps.gwt.client.InfoWindow;
import com.google.maps.gwt.client.InfoWindowOptions;
import com.google.maps.gwt.client.LatLng;
import com.google.maps.gwt.client.MapOptions;
import com.google.maps.gwt.client.MapTypeId;
import com.google.maps.gwt.client.Marker;
import com.google.maps.gwt.client.Marker.ClickHandler;
import com.google.maps.gwt.client.MarkerOptions;
import com.google.maps.gwt.client.MouseEvent;

public class PlaceView extends Composite implements Editor<PlaceProxy> {

	private static PlaceViewUiBinder uiBinder = GWT.create(PlaceViewUiBinder.class);

	interface PlaceViewUiBinder extends UiBinder<Widget, PlaceView> {
	}

	private GoogleMap map;

	@UiField
	@Path("name")
	CustomValueBoxEditorDecorator<String> nameTb;

	@UiField
	@Path("latitude")
	NumberLabel<Double> latitude;

	@UiField
	@Path("longitude")
	NumberLabel<Double> longitude;

	public PlaceView() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	protected void onLoad() {
		super.onLoad();

		final MapOptions myOptions = MapOptions.create();
		myOptions.setZoom(14.0);
		myOptions.setMapTypeId(MapTypeId.ROADMAP);

		LatLng position = LatLng.create(latitude.getValue(), longitude.getValue());

		map = GoogleMap.create(Document.get().getElementById("mapsDiv"), myOptions);
		map.setCenter(position);

		MarkerOptions markerOptions = MarkerOptions.create();
		markerOptions.setPosition(position);
		markerOptions.setMap(map);
		final Marker marker = Marker.create(markerOptions);

		InfoWindowOptions infoWindowOpts = InfoWindowOptions.create();
		infoWindowOpts.setContent("<b>" + nameTb.asEditor().getValue() + "</b>");

		final InfoWindow infoWindow = InfoWindow.create(infoWindowOpts);
		infoWindow.open(map);

		marker.addClickListener(new ClickHandler() {

			@Override
			public void handle(MouseEvent event) {
				infoWindow.open(map, marker);
			}
		});
	}
}
